package com.qupai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qupai.constant.StatusConstant;
import com.qupai.domain.dto.AdminLoginDTO;
import com.qupai.domain.entity.Admin;
import com.qupai.domain.vo.AdminLoginVO;
import com.qupai.exception.AdminException;
import com.qupai.interceptor.JwtTokenAdminInterceptor;
import com.qupai.mapper.AdminMapper;
import com.qupai.properties.JwtClaimsConstant;
import com.qupai.properties.JwtProperties;
import com.qupai.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qupai.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 管理表，存管理员信息 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-27
 */
@Service
@RequiredArgsConstructor
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    private final AdminMapper adminMapper;
    private final JwtProperties jwtProperties;

    @Override
    public AdminLoginVO login(AdminLoginDTO adminLoginDTO) {

        //根据用户名查数据库
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(Admin::getUsername,adminLoginDTO.getUsername());
        Admin admin = adminMapper.selectOne(wrapper);

        //判断是否存在改管理员
        if(admin==null){
            throw new AdminException("账号不存在");
        }

        //判断密码是否正确
        if(admin.getPassword() != adminLoginDTO.getPassword()){
            throw new AdminException("密码错误");
        }

        //判断账号是否被禁用
        if(admin.getStatus() == StatusConstant.DISABLE)
        {
            throw new AdminException("账号被禁用");
        }

        //登录成功后返回jwt令牌
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.ADMIN_ID,admin.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);


        return AdminLoginVO.builder()
                .id(admin.getId())
                .username(admin.getUsername())
                .token(token)
                .build();
    }
}
